import { ElMessage } from 'element-plus'
import type { MessageHandler } from 'element-plus'

class FeedbackService {
    private static instance: FeedbackService
    private wsMessage: MessageHandler | null = null
    private isReconnecting = false
    private connectingTimer: NodeJS.Timeout | null = null
    private connectingCount = 0

    private constructor() {}

    public static getInstance(): FeedbackService {
        if (!FeedbackService.instance) {
            FeedbackService.instance = new FeedbackService()
        }
        return FeedbackService.instance
    }

    // WebSocket 连接提示
    public showWSConnecting() {
        this.closeWSMessage()
        this.connectingCount = 0
        
        // 创建消息
        this.wsMessage = ElMessage({
            message: '正在连接 WebSocket...',
            type: 'info',
            duration: 0,
            grouping: true,
        })

        // 设置定时器，每500ms更新一次提示文本
        this.connectingTimer = setInterval(() => {
            this.connectingCount = (this.connectingCount + 1) % 4
            const dots = '.'.repeat(this.connectingCount)
            ElMessage.closeAll()
            this.wsMessage = ElMessage({
                message: `正在连接 WebSocket${dots}`,
                type: 'info',
                duration: 0,
                grouping: true,
            })
        }, 500)
    }

    // WebSocket 连接成功提示
    public showWSConnected() {
        this.closeWSMessage()
        
        // 显示成功消息
        ElMessage({
            message: 'WebSocket 连接成功',
            type: 'success',
            duration: 2000,
            grouping: true,
        })

        this.isReconnecting = false
    }

    // WebSocket 重连提示
    public showWSReconnecting() {
        // 如果已经在重连中，不重复提示
        if (this.isReconnecting) return
        
        this.isReconnecting = true
        this.connectingCount = 0
        this.closeWSMessage()

        // 创建重连消息
        this.wsMessage = ElMessage({
            message: '正在重新连接...',
            type: 'warning',
            duration: 0,
            grouping: true,
        })

        // 设置定时器，更新重连提示
        this.connectingTimer = setInterval(() => {
            this.connectingCount = (this.connectingCount + 1) % 4
            const dots = '.'.repeat(this.connectingCount)
            ElMessage.closeAll()
            this.wsMessage = ElMessage({
                message: `正在重新连接${dots}`,
                type: 'warning',
                duration: 0,
                grouping: true,
            })
        }, 500)
    }

    // 关闭所有提示
    private closeWSMessage() {
        if (this.connectingTimer) {
            clearInterval(this.connectingTimer)
            this.connectingTimer = null
        }
        ElMessage.closeAll()
        this.wsMessage = null
    }
}

// 导出单例实例
export const feedback = FeedbackService.getInstance() 